﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys;
using PARK.Consumer.Entitys.Dto.ConsumMachine;
using PARK.Consumer.Entitys.Dto.ConsumMerchant;
using PARK.Consumer.Interfaces;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace PARK.Consumer.ConsumMerchant
{
    /// <summary>
    /// 商户档案服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "ConsumMerchant", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumMerchantService : IConsumMerchantService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ConsumMerchantEntity> _consumMerchantRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ConsumMerchantService"/>类型的新实例
        /// </summary>
        public ConsumMerchantService(
            ISqlSugarRepository<ConsumMerchantEntity> consumMerchantRepository,
            IUserManager userManager)
        {
            _consumMerchantRepository = consumMerchantRepository;
            _db = _consumMerchantRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取商户档案
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = await _db.Queryable<ConsumMerchantEntity>().FirstAsync(p => p.MerchantId == id);
            var output = entity.Adapt<ConsumMerchantInfoOutput>();
            var machines = _db.Queryable<ConsumMachineEntity>()
              .Where(p => p.MerchantId.Equals(id))
              .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
              .ToList()
              .Select(a => a.Adapt<ConsumMachineListOutput>())
              .ToList();

            output.machines = machines;
            return output;
        }

        /// <summary>
		/// 获取商户档案列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ConsumMerchantListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "merchantId" : input.sidx;
                var data = await _db.Queryable<ConsumMerchantEntity>()
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                    .Where(d => d.IsDeleted != 1)
                    .WhereIF(!string.IsNullOrEmpty(input.merchantId), p => p.MerchantId.Contains(input.merchantId))
                    .WhereIF(!string.IsNullOrEmpty(input.merchantCode), p => p.MerchantCode.Contains(input.merchantCode))
                    .WhereIF(!string.IsNullOrEmpty(input.merchantName), p => p.MerchantName.Contains(input.merchantName))
                    .WhereIF(!string.IsNullOrEmpty(input.chargepername), p => p.Chargepername.Contains(input.chargepername))
                    .WhereIF(!string.IsNullOrEmpty(input.chargepertel), p => p.Chargepertel.Contains(input.chargepertel))
                    .Select(it => new ConsumMerchantListOutput
                    {
                        merchantId = it.MerchantId,
                        merchantCode = it.MerchantCode,
                        merchantName = it.MerchantName,
                        chargepername = it.Chargepername,
                        chargepertel = it.Chargepertel,
                        remarks = it.Remarks,
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<ConsumMerchantListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }

        /// <summary>
        /// 新建商户档案
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ConsumMerchantCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                //检查是否重复
                var et = _db.Queryable<ConsumMerchantEntity>()
                .Where(d => d.MerchantCode.Equals(input.merchantCode) && d.IsDeleted != 1 && d.CompanyId == userInfo.companyId)
                .ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.CON1004, "商户编码[" + input.merchantCode + "]已存在！");
                }
                et = _db.Queryable<ConsumMerchantEntity>()
                    .Where(d => d.MerchantName.Equals(input.merchantName) && d.IsDeleted != 1 && d.CompanyId == userInfo.companyId)
                    .ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.CON1005, "商户名称[" + input.merchantName + "]已存在！");
                }
                var entity = input.Adapt<ConsumMerchantEntity>();
                entity.MerchantId = YitIdHelper.NextId().ToString();
                entity.CreateDate = entity.LastUpdateDate = DateTime.Now;
                entity.CreateUser = entity.LastUpdateUser = _userManager.User.Id;
                entity.CreateUserName = entity.LastUpdateUserName = _userManager.User.RealName;
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1000);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }

        /// <summary>
        /// 更新商户档案
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ConsumMerchantUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                //检查是否重复
                var et = _db.Queryable<ConsumMerchantEntity>()
                .Where(d => d.MerchantCode.Equals(input.merchantCode) && d.IsDeleted != 1 && !d.MerchantId.Equals(input.merchantId) && d.CompanyId == userInfo.companyId)
                .ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.CON1004, "商户编码[" + input.merchantCode + "]已存在！");
                }
                et = _db.Queryable<ConsumMerchantEntity>()
                    .Where(d => d.MerchantName.Equals(input.merchantName) && d.IsDeleted != 1 && !d.MerchantId.Equals(input.merchantId) && d.CompanyId == userInfo.companyId)
                    .ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.CON1005, "商户名称[" + input.merchantName + "]已存在！");
                }
                var entity = input.Adapt<ConsumMerchantEntity>();
                entity.LastUpdateDate = DateTime.Now;
                entity.LastUpdateUser = _userManager.User.Id;
                entity.LastUpdateUserName = _userManager.User.RealName;
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }

        /// <summary>
        /// 删除商户档案
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                //检查是否存在正在用的消费机
                var list = _db.Queryable<ConsumMachineEntity>().Where(d => d.IsDeleted != 1 && d.MerchantId.Equals(id)).ToList();
                if (list != null && list.Count > 0)
                {
                    throw PARKException.Oh(ErrorCode.CON1006, "该商户下存在正在使用的消费机，无法删除！");
                }
                var entity = await _db.Queryable<ConsumMerchantEntity>().FirstAsync(p => p.MerchantId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                entity.DeleteUser = _userManager.User.Id;
                entity.DeleteUserName = _userManager.User.RealName;
                entity.DeleteDate = DateTime.Now;
                entity.IsDeleted = 1;
                var isOk = await _db.Updateable(entity).UpdateColumns(d => new { d.DeleteDate, d.IsDeleted, d.DeleteUser }).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
    }
}
